package com.gouda.temporary.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class CommonUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtils.class);

    public static <T> T gsonParseObject(String text, Class<T> clazz) {
        try {
            return new GsonBuilder().disableHtmlEscaping().create().fromJson(text, clazz);
        } catch (Throwable e) {
            LOGGER.error("Gson fromJson error", e);
            return null;
        }
    }

    public static String gsonToJson(Object object) {
        try {
            return new GsonBuilder().disableHtmlEscaping().create().toJson(object);
        } catch (Throwable e) {
            LOGGER.error("Gson toJson error", e);
            return "";
        }
    }


    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");

    public static String genOrderId() {
        return sdf.format(new Date());
    }

    private static final SimpleDateFormat sdf_now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String getNow() {
        return sdf_now.format(new Date());
    }

    /**
     * 获取客户端APP请求body内容
     * @param request http请求
     * @return body内容
     */
    public static String getRequestBodyContent(HttpServletRequest request) {
        int contentLen = request.getContentLength();
        if (contentLen == 0) {
            return "";
        }

        try {
            InputStream ins = request.getInputStream();
            byte[] content  = new byte[contentLen];
            int readLen     = ins.read(content, 0, contentLen);

            if (readLen > 0) {
                return new String(content, 0, readLen, "utf-8");
            }

            return "";
        } catch (IOException e) {
            LOGGER.error("Read request error.", e);
            return "";
        } catch (Exception e) {
            LOGGER.error("Read request fail", e);
            return "";
        }
    }

    /**
     * 解析微信支付系统的remark信息
     * @param remark remark信息
     * @return 解析结果
     */
    public static Map<String, String> decodeFromWeChatRemark(String remark) {
        HashMap<String, String> decodeMap = new HashMap<String, String>();

        String[] kvs = remark.substring(1, remark.length() -1) .split(",");
        for (String kv : kvs) {
            int spIdx = kv.indexOf('=');
            if (spIdx == -1) {
                continue;
            }

            decodeMap.put(kv.substring(0, spIdx).trim(), kv.substring(spIdx + 1, kv.length()).trim());
        }

        return decodeMap;
    }

    /**
     * 通过交易状态获取交易码
     * @param TransState 交易状态
     * @return 交易码
     */
    public static String getTransCodeByTradeStatus(String TransState) {
        if("WAIT_BUYER_PAY".equals(TransState))
            return "00";
        else if("TRADE_SUCCESS".equals(TransState))
            return "01";
        else if("TRADE_CLOSED".equals(TransState))
            return "04";
        else if("TRADE_CANCEL".equals(TransState))
            return "05";
        else if("TRADE_FAIL".equals(TransState))
            return "02";
        else
            return "00";
    }

    /**
     * 生成微信的remark信息
     * @param decodeMap 微信系统返回预支付订单信息
     * @return remark信息
     */
    public static String genWeChatRemark(HashMap<String, String> decodeMap) {
        return decodeMap.toString();
    }

    private CommonUtils() {}
}
